import SessionModel from "~/models/SessionModel";

export default defineEventHandler(async event => {
    // auth payload
    const { _id } = event.context.auth;

    // get page params
    let { page, itemPerPage } = getQuery(event);
    itemPerPage = itemPerPage ? +itemPerPage : 8;

    // get page count
    const [result] = await SessionModel.aggregate()
        .match({ user_id: _id })
        .group({ _id: '$user_id', itemCount: { $sum: 1 } });

    // get page
    const pageCount = result ? Math.ceil(result.itemCount / itemPerPage) : 1;
    page = page ? Math.min(+page, pageCount) : 1;

    // select items
    const list = await SessionModel.aggregate()
        .match({ user_id: _id })
        .project({ _id: 0, id: '$_id', title: 1, content: 1 })
        .skip((page - 1) * itemPerPage)
        .limit(itemPerPage);

    return {
        code: 0,
        msg: 'OK',
        data: { list, page, pageCount },
    };
});